import hashlib

from wine import settings
from redis import Redis
from wechatpy import WeChatClient, WeChatPay
from wechatpy.session.redisstorage import RedisStorage

from wxchat.models import WxUserInfo

redis_client = Redis.from_url(settings.REDIS_URL)
session_interface = RedisStorage(
    redis_client,
    prefix="wechatpy"
)


def md5_encrypt(key):
    m = hashlib.md5()
    m.update(key.encode("utf-8"))
    return m.hexdigest()


def get_openid_from_header(request):
    openid = request.META.get('HTTP_OPENID', b'')
    return openid


def wxClient():
    """
    创建微信客户端对象
    :return:
    """
    client = WeChatClient(settings.WECHAT_APPID, settings.WECHAT_SECRET, session=session_interface)
    return client


def WeixinPay():
    """
     创建微信支付对象
    :return:
    """
    wxPay = WeChatPay(appid=settings.WECHAT_APPID, api_key=settings.MCH_KEY, mch_id=settings.MCH_ID)
    return wxPay


def get_user_by_openid(openid):
    user = WxUserInfo.objects.filter(openid=openid).first()
    return user

